package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author: Zheng
 * Date:   2024/3/1  12:49
 * Package：com.sky.service.impl
 * Description：
 * Version：1.0
 */
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * @param begin
     * @param end
     * @description： 营业额统计
     * @date：2024/3/1 12:53
     * @return：
     */
    @Override
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {

        //构造dateList数据 日期数据 2024-02-23
        List<LocalDate> dateList = getDateList(begin, end);

        //构造turnoverList数据
        List<Double> turnoverList = new ArrayList<>();
        dateList.forEach(date -> {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("status", Orders.COMPLETED);//状态为 5 已完成的订单
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            Double turnover = ordersMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        });
        //封装TurnoverReportVO返回

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * @description： 构造dateList数据
     * @date：2024/3/1 16:02
     * @return：
     **/
    private List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin); //2-23
        while (!begin.equals(end)) {
            begin = begin.plusDays(1); //2-29
            dateList.add(begin);
        }
        return dateList;
    }

    /**
     * @param begin
     * @param end
     * @description： 用户统计
     * @date：2024/3/1 16:00
     * @return：
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //构造dateList数据
        List<LocalDate> dateList = getDateList(begin, end);

        //构造totalUserList数据
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//2024-02-23 00:00
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//2024-02-23 23:59:59
            //查询user表
            Integer totalUser = userMapper.countBy(null, endTime);
            totalUserList.add(totalUser);

            //构造newUserList数据
            Integer newUser = userMapper.countBy(beginTime, endTime);
            newUserList.add(newUser);

        }

        //封装并返回UserReportVO
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    /**
     * @param begin
     * @param end
     * @description： 订单统计
     * @date：2024/3/1 16:29
     * @return：
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //构造dateList数据
        List<LocalDate> dateList = getDateList(begin, end);
        //构造每日订单数据orderCountList
        List<Integer> orderCountList = new ArrayList<>();
        //构造每日有效订单数据validOrderCountList
        List<Integer> validOrderCountList = new ArrayList<>();
        //订单总数
        Integer totalOrderCount = 0;
        //有效订单数
        Integer validOrderCount = 0;
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            //获取每日订单总数
            Integer dailyOrderCount = ordersMapper.countByMap(map);
            //每日订单数列表orderCountList
            orderCountList.add(dailyOrderCount);
            //获取每日有效订单
            map.put("status", Orders.COMPLETED);
            Integer dailyValidOrderCount = ordersMapper.countByMap(map);
            //每日有效订单数列表
            validOrderCountList.add(dailyValidOrderCount);
            //获取订单总数
            totalOrderCount += dailyOrderCount;
            //获取有效订单总数
            validOrderCount += dailyValidOrderCount;
        }

        //构造订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = 1.0 * validOrderCount / totalOrderCount;
        }
        //构造并返回OrderReportVO
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * @param begin
     * @param end
     * @description： 查询销量top10
     * @date：2024/3/1 17:24
     * @return：
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOS = ordersMapper.getTop10(beginTime, endTime, Orders.COMPLETED);

        //构造商品名称列表
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        for (GoodsSalesDTO goodsSalesDTO : goodsSalesDTOS) {
            String name = goodsSalesDTO.getName();
            nameList.add(name);
            Integer number = goodsSalesDTO.getNumber();
            //构造销量列表
            numberList.add(number);
        }


        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * @param response
     * @description： 导出数据报表
     * @date：2024/3/2 20:43
     * @return：
     */
    @Override
    public void export(HttpServletResponse response) {
        //获取30天前的日期对象和当前日期前一天的日期对象
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //调用工作台的方法，获取近30天营业额数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        //基于模版文件创建工作簿对象（类加载器获取文件类路径）
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板创建新的Excel文件对象
            Workbook workbook = new XSSFWorkbook(in);
            //创建sheet表对象
            Sheet sheet = workbook.getSheetAt(0);
            //获取第二行第二个单元格，设置第表格日期数据
            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            //获取第四行
            Row row = sheet.getRow(3);
            //获取单元格,填充数据
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            //获取第五行,获取单元格，填充数据
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            int i = 7;
            while (!begin.isAfter(end)) {
                businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
                row = sheet.getRow(i++);
                row.getCell(1).setCellValue(begin.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
                begin = begin.plusDays(1);
            }
            //通过输出流将文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            workbook.write(out);
            //关闭流
            out.flush();
            out.close();
            workbook.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
